/*
 * RenzoMesh.cpp
 *
 *  Created on: Aug 30, 2009
 *      Author: sonhua
 */

#include "RenzoMustHave.h"
#include "RenzoPrecompiled.h"
#include "RenzoMesh.h"
#include "RenzoMeshMd2.h"
#include "RenzoResourceManager.h"

namespace Renzo {

Mesh::Mesh() {
	
}

Object* Mesh::create() {
	return new Mesh;
}

Mesh::~Mesh() {
	// ask ResourceManager to dispose all polygon groups
	PolygonGroupList::iterator i;
	ResourceManager* rm = Renzoderer::instance()->getResourceManager();
	for (i = polygonGroups.begin(); i != polygonGroups.end(); ++i) 
		rm->disposeObject(*i);
}

void Mesh::addPolygonGroup(PolygonGroup* p) {
	// maintain a reference to sub meshes.
	polygonGroups.push_back(p);
}

BoundingBox* Mesh::getBoundingBoxAABB() {
	bb.min = INF_MAX;
	bb.max = INF_MIN;

	// union all bounding boxes
	PolygonGroupList::iterator i;
	for (i = polygonGroups.begin(); i != polygonGroups.end(); ++i) {
		BoundingBox* box = (*i)->getBoundingBoxAABB();
		bb.min = rzMin3(bb.min, box->min);
		bb.max = rzMax3(bb.max, box->max);
	}

	bb.center = (bb.min + bb.max) * 0.5f;
	bb.dim = bb.max - bb.min;
	bb.radius = bb.dim.length() * 0.5f;

	return &bb;
}

void Mesh::update(int delta) {
	PolygonGroupList::iterator i;
	for (i = polygonGroups.begin(); i != polygonGroups.end(); ++i) {
		(*i)->update(delta);
	}
}

void Mesh::transform(const Matrix4& mat) {
	matTransform = mat;

	PolygonGroupList::iterator i;
	for (i = polygonGroups.begin(); i != polygonGroups.end(); ++i) {
		(*i)->transform(mat);		
	}
}

void Mesh::render() {
	PolygonGroupList::iterator i;
	for (i = polygonGroups.begin(); i != polygonGroups.end(); ++i) {
		(*i)->render();		
	}
}

}
